package com.black.utils.file.compress.jar.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ylx
 */
@Getter
@Setter
public class PackageTreeInfo extends JavaInfo {
    private int level;
    private PackageTreeInfo parent;
    private Map<String, PackageTreeInfo> children;
    private List<ClassInfo> classes;

    public static PackageTreeInfo root() {
        return new PackageTreeInfo(null, "src");
    }

    public PackageTreeInfo(PackageTreeInfo parent, String name) {
        super(name);
        this.level = parent == null ? 0 : parent.level + 1;
        this.parent = parent;
        this.children = null;
    }

    public void addClass(ClassInfo classInfo) {
        if (classes == null) {
            classes = new ArrayList<>();
        }
        if (children == null) {
            children = new HashMap<>();
        }
        String[] names = classInfo.name.split("/");
        if (level >= names.length) {
            return;
        }
        if (level == names.length - 1) {
            classes.add(classInfo);
            return;
        }
        String name = names[level];
        PackageTreeInfo levelChild = children.get(name);
        if (levelChild == null) {
            levelChild = new PackageTreeInfo(this, name);
            children.put(name, levelChild);
        }
        levelChild.addClass(classInfo);
    }

    public PackageTreeInfo getTarget(String[] names) {
        PackageTreeInfo leaf = children.get(names[level]);
        if (level == names.length - 1){
            return leaf;
        }
        return leaf.getTarget(names);
    }
}
